import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:ws_group_chat/pages/host/host_chat_page.dart';
import 'package:ws_group_chat/provider/host_data.dart';

class HostWaitPage extends StatefulWidget {
  const HostWaitPage({super.key});

  @override
  State<HostWaitPage> createState() => _HostWaitPageState();
}

class _HostWaitPageState extends State<HostWaitPage> {
  late final HostData _hostData;
  bool _isToChatPage = false;

  @override
  void dispose() {
    if (!_isToChatPage) {
      _hostData.close();
    }
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    _hostData = context.read<HostData>();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('等待玩家'),
        backgroundColor: Colors.transparent,
      ),
      body: Consumer<HostData>(
        // 这里不使用 Selector 原因是appData的数据量不多，所以没必要使用Selector
        builder: (context, vm, child) {
          return Padding(
            padding: const EdgeInsets.symmetric(horizontal: 20),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text('${vm.playersCount}人已加入'),
                const SizedBox(height: 40, width: double.infinity),
                const Text('请分享二维码给其他玩家'),
                QrImageView(
                  data: vm.wsUrl!,
                  version: QrVersions.auto,
                  size: 200.0,
                ),
                const SizedBox(height: 16),
                Text(vm.wsUrl!, style: Theme.of(context).textTheme.bodyMedium),
                const Spacer(),
              ],
            ),
          );
        },
      ),
      floatingActionButton: // 开始游戏按钮
      Selector<HostData, int>(
        selector: (context, data) => data.playersCount,
        builder: (context, playersCount, child) {
          return SizedBox(
            width: double.infinity,
            child: ElevatedButton(
              onPressed: playersCount > 1
                  ? () {
                      _hostData.startChatRoom();
                      _isToChatPage = true;
                      Navigator.pushReplacement(
                        context,
                        MaterialPageRoute(
                          builder: (context) => const HostChatPage(),
                        ),
                      );
                    }
                  : null,
              style: ElevatedButton.styleFrom(
                padding: const EdgeInsets.symmetric(vertical: 16),
              ),
              child: const Text('开启聊天室'),
            ),
          );
        },
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
    );
  }
}
